;-function(window){
    "use strict";
    var tempUList,fairyWin,mainWin,chatCurrent,chatList,chatWin,config, ready = {
        getPath: function(){
            var js = document.scripts, script = js[js.length - 1], jsPath = script.src;
            if(script.getAttribute('merge')) return;
            return jsPath.substring(0, jsPath.lastIndexOf("/") + 1);
        }()
    };
    {
        tempUList = [];
        fairyWin = null;
        mainWin = null;
        chatWin = null;
        chatCurrent = null;
        chatList = [];
    }
    //默认配置
    config = {
        mainArea: ['260px', '520px'],
        chatArea: ['800px', '520px'],
        fairyArea:['100px', '30px'],
        skin: 'layui-layer-demo',
        anim: 0,
        sendCallBack : function(){},
        temporary:false
    };
    //加载css
    ready.loadStyles = function(){
        var csslist = [
            "skin/naiveIM.css",
            "skin/icono.min.css"
        ];
        var head = $('head')[0];
        $(csslist).each(function(){
            var link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = naive.path + this;
            head.appendChild(link);
        });
    };
    ready.init = function(data){
        ready.mine = data.mine;
        ready.friend = data.friend;
        ready.session = data.session;
        ready.userList = [];
        $(ready.friend).each(function(index,group){
            $(group.list).each(function(index,user){
                ready.userList.push(user);
            });
        });
        $('.naive-user').html(ready.mine.username);//用户名
        $('.naive-remark').val(ready.mine.remark);//个性签名
        ready.status(ready.mine.status);//更新用户状态
        ready.cd(ready.mine.background);//设定背景
        //写入好友
        ready.drawFriendList();
        //写入会话
        ready.drawSessionList();
    };
    //最小化的窗口 事件初始化在这里
    ready.initFairyEvent = function(){
        $('.naive-fairy').click(function(){
            ready.toggle();
        });
    };
    //主窗口 事件初始化
    ready.initEvent = function(){
        layui.use('element', function(){//激活选项卡
            //注册点击聊天事件
            $('.naive-list-user li').click(function(){
                var id = $(this).attr('id');
                if(id){
                    id = id.substr(11,id.length);
                    if(chatCurrent && chatCurrent.id == id){
                        return;
                    }
                    var user = ready.getUser(id);
                    var cu = $('#naive-list-'+id+' img');
                    if(cu && cu.length > 0){//打开窗口 停止播放新消息动画
                        cu.removeClass('naive-shake-horizontal');
                    }
                    ready.chat(user);
                }
            });
        });
        //注册底部按钮事件
        $('.naive-bottom-about').click(function(){
            ready.about();
        });
        //关闭按钮
        $('.naive-close').click(function(){
            ready.toggle();
        });
    };
    ready.about = function(){
        layui.use('layer', function(){
            layer.alert('版本：'+naive.v,{title:'naiveIM'});
        });
    };
    ready.toggle = function(){
        $(mainWin).toggle();
        $(fairyWin).toggle();
    }
    //变装 更换皮肤
    ready.cd = function(url){
        if(!url){
            url = naive.path+'skin/bg.png';
        }
        $('.naive-box').css('background-image','url('+url+')');
        $('.naive-chat-win').css('background-image','url('+url+')');
    };
    ready.setCache = function(){//TODO 暂时不用
        var cache = {chatList:chatList,data:ready.data};
        localStorage.setItem('naiveCache', JSON.stringify(cache));
    };
    ready.loadCache = function(){//TODO 暂时不用
        var cache = localStorage.getItem('naiveCache');
        if(cache){
            cache = JSON.parse(cache);
            chatList = cache.chatList;
            ready.data = cache.data;
        }
    };
    //修改用户窗口或者好友在线状态
    ready.status = function(status,id){
        if(id){//根据id修改状态
            var user = ready.getUser(id);
            if(user){
                user.status = 'hide';
                var naiveStatus = $('#naive-list-'+id);//更新用户状态
                if(status == "online"){
                    naiveStatus.removeClass('naive-user-gray');
                }else{
                    naiveStatus.removeClass('naive-user-gray');
                    naiveStatus.addClass('naive-user-gray');
                }
            }
        }else{//修改使用者状态
            var naiveStatus = $('.naive-status');//更新用户状态
            if(status == "online"){
                naiveStatus.html('<span class="naive-status-ol">●</span>');
            }else{
                naiveStatus.html('<span class="naive-status-hide">●</span>');
            }
        }

    };
    //删除好友
    ready.delFriend = function(idList){
        var newUserList = [];
        $(ready.userList).each(function(userIndex,user){
            var delUser = null;
            $(idList).each(function(idIndex,id){
                if(id == user.id){
                    delUser = user;
                }
            });
            if(!delUser){
                newUserList.push(user);
            }
        })
        ready.userList = newUserList;//删除完毕

        $(ready.friend).each(function(frindex,group){
            var nglist = [];
            $(group.list).each(function(uindex,user){
                var duser = null;
                $(idList).each(function(idindex,id){
                    if(id == user.id){
                        duser = user;
                    }
                });
                if(!duser){
                    nglist.push(user);
                }
            });
            group.list = nglist;
        });
        var newSessionList = [];
        $(ready.session).each(function(sIndex,sid){
            var delid = null
            $(idList).each(function(idindex,id){
                if(id != sid){
                    delid = sid;
                }
            });
            if(!delid){
                newSessionList.push(sid);
            }
        });
        ready.drawFriendList();//重绘好友列表
        ready.drawSessionList();
    }
    ready.addFriend = function(friend){
        var rfriend = ready.friend;
        $(friend).each(function(findex,fgroup){
            var exgroup = null;
            $(rfriend).each(function(rfindex,rfgroup){
                if(fgroup.id == rfgroup.id){
                    exgroup = rfgroup;
                }
            });
            if(exgroup){//已经存在分组
                var user = null;
                $(fgroup.list).each(function(fgIndex,fgUser){
                    user = ready.getUser(fgUser.id);
                    if(!user){//不存在这个用户，为新用户。
                        exgroup.list.push(fgUser);
                        ready.userList.push(fgUser);
                    }
                });
            }else{//不存在分组
                var tgroup = {
                    groupname: fgroup.groupname,
                    show: fgroup.show,
                    id: fgroup.id,
                    list: []
                };
                rfriend.push(tgroup);
                $(fgroup.list).each(function(fgIndex,fgUser){
                    var user = ready.getUser(fgUser.id);
                    if(!user){
                        tgroup.list.push(fgUser);
                        ready.userList.push(fgUser);
                    }
                });
            }
        });

        ready.drawFriendList(rfriend);//重绘好友列表
    };
    //创建聊天窗口
    ready.chat = function(user){
        var duser = ready.getUser(user.id);
        if(!duser){//临时会话用户 加入特殊标识
            tempUList.push(user);
            user.tempUser = true;
        }
        var chatUser;
        $(chatList).each(function(index,eUser){
            if(eUser.id == user.id){
                chatUser = eUser;
            }
        });
        if(!chatUser){//会话列表不存在 添加进去
            chatList.push(user);
        }
        chatCurrent = user;
        if(!chatWin){//是否有聊天窗口打开
            //打开新窗口
            ready.drawChat(user,function(){
                ready.initChatEvent();
                ready.switch(user);
            });
        }else{
            ready.switch(user);
        }
    };
    //重绘聊天窗口左侧对话列表
    ready.REDrawChatUserItem = function(){
        if(chatCurrent){
            var chatUser = $('.naive-chat-user').html('');
            $(chatList).each(function(index,user){
                var avatar = user.avatar&&user.avatar!='undefined'?user.avatar:naive.path+'skin/avatar.png';
                var status = '';
                if(user.status != 'online'){
                    status = ' naive-user-gray';
                }
                var shake = '';
                if(user.shake == true){
                    shake = ' naive-shake-horizontal';
                }
                var current = '';
                if(chatCurrent.id == user.id){
                    current = ' naive-user-white';
                }
                var item = $('<div class="naive-chat-user-item'+current+'" id="naive-chat-user-'+user.id+'"><img src="'+avatar+'" class="'+status+shake+'"><p>'+user.username+'</p></div>');
                var close = $('<a class="naive-ico naive-chat-user-close"></a>');
                close.click(function(event){
                    ready.btnClose(user.id);
                    event.stopPropagation();
                });
                item.append(close);
                item.click(function(){
                    ready.chat(user);
                });
                chatUser.append(item);
            });
        }
    };
    //更换聊天对象
    ready.switch = function(user){
        var records = $('.naive-chat-records');
        records.empty();
        var avatar = user.avatar&&user.avatar!='undefined'?user.avatar:naive.path+'skin/avatar.png';
        $('.naive-chat-top-user img').attr('src',avatar);
        var username = user.username;
        if(user.tempUser){
            username = '[临时会话]' + username;
        }
        $('.naive-chat-top-user span').html(username);
        user.shake = false;
        $(user.records).each(function(index,rec){
            if(rec.type == 'receive'){
                //对方发的
                ready.drawReceive(avatar,rec);
            }else{
                //我发的
                ready.drawSend(rec);
            }
        });
        chatCurrent = user;
        ready.REDrawChatUserItem();
    };
    //绘制聊天窗口
    ready.drawChat = function(user,callback){
        var content = '<div class="naive-chat">';
        content += '<div class="naive-chat-user">';//左侧
        content += '</div>';
        content += '<div class="naive-chat-win">';//右侧
        content += '<div class="naive-chat-top naive-chat-move">';
        content += '<div class="naive-chat-top-user">';
        content += '<img src=""/>';
        content += '<span></span>';
        content += '</div>';
        content += '</div>';

        content += '<div class="naive-chat-records">';//聊天记录
        content += '</div>';

        content += '<div class="naive-chat-send">';//下面的发送区域
        content += '<div class="naive-chat-tool">';//表情等按钮
        content += '<div><i class="icono-smile naive-content-box"></i></div>';
        content += '<div><i class="icono-image naive-content-box"></i></div>';
        content += '<div><i class="icono-folder naive-content-box"></i></div>';
        content += '</div>';

        content += '<div class="naive-chat-input">';//输入消息的地方
        content += '<textarea id="naive-chat-input-textarea" placeholder="Enter发送"></textarea>';
        content += '</div>';

        content += '<div class="naive-chat-btn">';//发送按钮啥的
        content += '<button class="layui-btn naive-chat-btn-send">发送</button>';
        content += '<button class="layui-btn naive-chat-btn-close">关闭</button>';
        content += '</div>';

        content += '</div>';
        content += '</div>';
        content += '<a class="naive-ico naive-chat-close"></a></div>';
        layui.use('layer', function(){
            chatWin = layer.open({
                type: 1,
                area: config.chatArea,
                skin: config.skin, //样式类名
                anim: config.anim,
                shade: 0,
                closeBtn: 0, //不显示关闭按钮
                resize: false,
                shadeClose: true, //开启遮罩关闭
                title: false,
                move: '.naive-chat-move',
                content: content,
                success:function(layero,index){//回调
                    if(typeof callback === 'function'){
                        callback(index);//窗体加载完毕
                    }
                }
            });
        });
    };

    //初始化聊天窗口事件
    ready.initChatEvent = function(){
        ready.cd(ready.mine.background);//刷新背景
        //快捷键
        $('#naive-chat-input-textarea').keydown(function (event) {
            if (event.keyCode == 13) {
                ready.send();
                return false;
            }
        });
        //注册chat 关闭事件
        $('.naive-chat-close').click(function(){
            layui.use('layer', function(){
                var i =layer.confirm('确定关闭窗口？', {
                    btn: ['关闭','取消'] //按钮
                },function(){
                    layer.close(i);
                    layer.close(chatWin);
                    chatList = [];
                    chatWin = null;
                    chatCurrent = null;
                });
            });
        });
        //注册关闭按钮事件
        $('.naive-chat-btn-close').click(function(){
            ready.btnClose();
        });
        //注册发送按钮事件
        $('.naive-chat-btn-send').click(function(){
            ready.send();
        });
        var records = $('.naive-chat-records');
        records.scrollTop(records[0].scrollHeight);
    };
    ready.btnClose = function(id){
        var u;
        if(id){
            u = ready.getUser(id)
        }else{
            u = chatCurrent;
        }
        var cl = [];
        if(u){
            $(chatList).each(function(index,user){
                if(user.id != u.id){
                    cl.push(user);
                }
            });
        }
        if(cl.length > 0){
            chatList = cl;
            u = chatList[0];
            ready.switch(u);
        }else{
            $('.naive-chat-close').click();
        }
    };
    ready.HTMLEncode = function(html){
        var temp = document.createElement("div");
        (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
        var output = temp.innerHTML;
        temp = null;
        return output;
    };
    //发送出消息
    ready.send = function(){
        if(!chatCurrent){
            return;
        }
        if(!chatCurrent.records){
            chatCurrent.records = [];
        }
        var naive_send_textarea = $('#naive-chat-input-textarea');
        var say = ready.HTMLEncode(naive_send_textarea.val());
        naive_send_textarea.val('');
        say = say.replace(/(^\s*)|(\s*$)/g, "");
        if(!say){
            return;
        }
        var now = ready.getNowFormatDate();
        var d = {type:'send',content:say,time:now};
        chatCurrent.records.push(d);
        if(chatCurrent.records.length > 40){//records 缓存只浏览器保存持20条，其余的聊天记录通过接口调取。
            chatCurrent.records = chatCurrent.records.splice(1,chatCurrent.records.length);
        }
        ready.drawSend(d);
        var csl = [chatCurrent.id];
        $(ready.session).each(function(index,id){
            if(csl != id){
                csl.push(id);
            }
        });
        ready.session = csl;
        ready.drawSessionList();
        config.sendCallBack({mine:ready.mine,recipient:chatCurrent,say:say});
    };
    ready.drawSend = function(data){
        var records = $('.naive-chat-records');
        var content = '<div class="naive-chat-records-recipient-right">';
        content += '<p>'+data.time+'</p><div class="naive-chat-records-recipient-content-right">';
        content += data.content;
        content += '</div>';
        var avatar = ready.mine.avatar&&ready.mine.avatar!='undefined'?ready.mine.avatar:naive.path+'skin/avatar.png';
        content += '<img src="'+avatar+'">';
        content += '</div>';
        records.append(content);
        records.scrollTop(records[0].scrollHeight);
    };
    //接收到消息
    ready.receive = function(data){
        if(!data){
            return;
        }
        var user = ready.getUser(data.send.id);//这个user是消息发送者
        if(user){//消息发送者一定要存在
            if(!user.records){
                user.records = [];
            }
            var content = data.content.replace(/(^\s*)|(\s*$)/g, "");
            if(!content){
                return;
            }
            var now = ready.getNowFormatDate();
            var d = {type:'receive',content:data.content,time:now};
            user.records.push(d);
            if(user.records.length > 20){//records 缓存只浏览器保存持20条，其余的聊天记录通过接口调取。
                user.records = user.records.splice(1,user.records.length);
            }
            if(chatCurrent && data.send.id == chatCurrent.id){//如果这条消息是发送给当前聊天对象则直接显示到页面上
                var avatar = user.avatar&&user.avatar!='undefined'?user.avatar:naive.path+'skin/avatar.png';
                ready.drawReceive(avatar,d);
            }else{//如果这条消息不是发送给当前聊天对象的时候 再左侧尝试获取这个人并且给他添加动画效果
                var cu = $('#naive-chat-user-'+user.id+' img');
                if(!cu || cu.length < 1){//如果这个人不存在的话 在主窗口添加动画
                    cu = $('#naive-list-'+user.id+' img');
                }
                user.shake = true;
                cu.addClass('naive-shake-horizontal');
            }
        }
    };
    ready.drawReceive = function(avatar,data){
        var records = $('.naive-chat-records');
        var content = '<div class="naive-chat-records-recipient">';
        content += '<img src="'+avatar+'"><p>'+data.time+'</p>';
        content += '<div class="naive-chat-records-recipient-content">';
        content += data.content;
        content += '</div>';
        content += '</div>';
        records.append(content);
        records.scrollTop(records[0].scrollHeight);
    };
    ready.getNowFormatDate = function() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
        return currentdate;
    }

    //绘制好友列表
    ready.drawFriendList = function(){
        var content = '<div class="layui-collapse naive-collapse">';
        $(ready.friend).each(function(index,group){
            content += '<div class="layui-colla-item naive-colla-item" naive-id="'+ group.id +'">';
            content += '<h2 class="layui-colla-title naive-colla-title">'+ group.groupname +'</h2>';
            var show = '';
            if(group.show){
                show = ' layui-show';
            }
            content += '<div class="layui-colla-content naive-colla-content'+show+'">';
            var userList = group.list;
            content += '<ul class="naive-list-user">';
            $(userList).each(function(index,user){
                var status = '';
                if(user.status != 'online'){
                    status = ' naive-user-gray';
                }
                content += '<li id="naive-list-'+user.id+'" class="'+status+'">';
                var avatar = user.avatar&&user.avatar!='undefined'?user.avatar:naive.path+'skin/avatar.png';
                content += '<img src="'+avatar+'"/>';
                content += '<div><span>'+user.username+'</span>';
                var remark = '　';
                if(user.remark && user.remark != undefined){
                    remark = user.remark;
                }
                content += '<p>'+remark+'</p></div>';
                content += '</li>';
            });
            content += '</ul>';
            content += '</div></div>';
        });
        content += '</div>';
        $('.naive-friend').html(content);
        layui.use('element', function(){});
    };
    ready.drawSessionList = function(){
        var session = $('.naive-session').html('');
        $(ready.session).each(function(index,id){
            var user = ready.getUser(id);
            if(user){
                var avatar = user.avatar&&user.avatar!='undefined'?user.avatar:naive.path+'skin/avatar.png';
                var remark = '　';
                if(user.remark && user.remark != undefined){
                    remark = user.remark;
                }
                var content = $('<div class="naive-session-user" id="naive-session-'+user.id+'"><img src="'+avatar+'"><div><span>'+user.username+'</span><p>'+remark+'</p></div></div>');
                content.click(function(){
                    ready.chat(user);
                });
                session.append(content);
            }else{
                //TODO
            }
        });
    }
    ready.getUser = function(id){
        if(!ready.userList){
            console.error('用户列表获取失败，可能未初始化或初始化失败导致。');
            return;
        }
        if(!id){
            console.error('参数不能为空。');
            return;
        }
        var u;
        $(ready.userList).each(function(index,user){
            if(id == user.id){
                u = user;
            }
        });
        if(!u && config.temporary){//从临时会话中取用户数据
            $(tempUList).each(function(index,user){
                if(id == user.id){
                    u = user;
                }
            });
        }
        return u;
    };

    //对外
    var naive = {
        v: '0.1',
        path: ready.getPath,
        config: function(opt, fn){
            config = $.extend({}, config, opt);
            return this;
        }
    };
    //初始化加载主窗口
    naive.creat = function(options,showType){
        if(showType == undefined){
            showType = true;
        }
        //1主体框架  关闭按钮在这层
        var content = '<div class="naive-box">';
        //2上半部分 包括姓名 状态 签名
        content += '<div class="naive-main"><div class="naive-move"></div><div class="naive-info">';
        content += '<div class="naive-top"><div class="naive-user"></div>';//姓名
        content += '<div class="naive-status"></div>';//状态
        content += '<input class="naive-remark naive-content-box" placeholder="编辑签名" value=""/></div>';

        content += '<div class="layui-tab naive-tab">';
        content += '<ul class="layui-tab-title naive-tab-title">';
        content += '<li class="layui-this naive-this"><i class="icono-user naive-content-box"></i></li>';
        content += '<li class="naive-this"><span><i class="icono-comment"></span></i></li>';
        content += '</ul>';
        content += '<div class="layui-tab-content naive-tab-content naive-content-box">';
        content += '<div class="layui-tab-item layui-show"><div class="naive-friend"></div></div><div class="layui-tab-item naive-session"></div>';
        content += '</div>';

        content += '<div class="naive-bottom">';
        content += '<div><i class="icono-search"></i></div><div><i class="icono-volumeMedium naive-content-box"></i></div><div><i class="icono-plus"></i></div><div class="naive-bottom-about"><i class="icono-hamburger"></i></div>';
        content += '</div>';

        content += '</div><</div>';

        content += '<a class="naive-ico naive-close"></a></div>';//关闭按钮在这里

        var fairy = '<div class="naive-fairy-win"><div class="naive-fairy">';
        fairy += '<div class="naive-fairy-user">我的会话</div>';//姓名
        fairy += '<div class="naive-status naive-fairy-status"></div></div>';//状态
        fairy += '</div>';
        layui.use('layer', function(){
            layer.open({
                type: 1,
                area: config.fairyArea,
                offset: 'rb',
                skin: config.skin, //样式类名
                anim: config.anim,
                shade: 0,
                closeBtn: 0, //不显示关闭按钮
                resize: false,
                shadeClose: true, //开启遮罩关闭
                title: false,
                content: fairy,
                success:function(layero,index){//回调
                    fairyWin = layero;
                    if(showType){
                        $(fairyWin).hide();
                    }
                    ready.initFairyEvent();
                }
            });
            layer.open({
                type: 1,
                area: config.mainArea,
                offset: 'rb',
                skin: config.skin, //样式类名
                anim: config.anim,
                shade: 0,
                closeBtn: 0, //不显示关闭按钮
                resize: false,
                shadeClose: true, //开启遮罩关闭
                title: false,
                move: '.naive-move',
                content: content,
                success:function(layero,index){//回调
                    mainWin = layero;
                    if(!showType){
                        $(mainWin).hide();
                    }
                    ready.initEvent();
                    if(options && typeof options.success === 'function'){
                        options.success(layero,index);
                    }
                }
            });
        });

        return naive;
    };

    naive.init = function(data,callback){
        if((typeof data=='object')&&data.constructor==Object){
            ready.init(data);
            if(typeof callback === 'function'){
                callback();
            }
        }else{
            console.error('初始化数据格式错误。');
            return;
        }
    };

    naive.refresh = function(data){
    };

    naive.chat = function(data){
        var user = null;
        if((typeof data=='string')&&data.constructor==String){//传入用户id
            user = ready.getUser(data);//获取用户信息
        }else if((typeof data=='object')&&data.constructor==Object){//传入用户对象
            user = data;
        }else{
            console.error('参数应为用户id或者在开启临时会话模式下传入用户对象。');
            return;
        }
        if(user){
            ready.chat(user);
        }
    };
    //修改状态。如果不传入id 则修改当前登陆者状态。
    naive.status = function(status,id){
        ready.status(status,id);
    };
    //发送消息
    naive.send = function(callback){
        if(typeof callback === 'function'){
            config.sendCallBack = callback;
        }else{
            console.error(callback + 'Is not a function.');
        }
    };
    //添加好友
    naive.addFriend = function(friend){
        if(!friend){
            return;
        }
        ready.addFriend(friend);
    }
    //删除好友
    naive.delFriend = function(idList){
        if(idList && idList.length > 0){
            ready.delFriend(idList);
        }
    };
    //接收消息
    naive.receive = function(data){
        ready.receive(data);
    };
    ready.loadStyles();
    window.Naive = naive;

}(window);